#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define DATA_LEN 256
unsigned char data[DATA_LEN];
const int data_len = DATA_LEN;

int stream_read_data(unsigned char *buff, int length, int off)
{
    int len, remain_len;
    remain_len = data_len - off;
    if (remain_len > 0)
    {
        if (remain_len >= length)
            len = length;
        else
            len = remain_len;
    }
    else
        return 0;
    memcpy(buff, data + off, len);

    return len;
}

void init_data(int mode)
{
    // 1.读取文件
    if (mode == 1)
    {
        FILE *fp = fopen("1_stream_流式文件读.c", "r");
        fread(data, DATA_LEN, 1, fp);
        fclose(fp);
    }
    // 2.随机初始化
    else if (mode == 2)
    {
        srand(time(NULL));
        for (int i = 0; i < DATA_LEN; i++)
        {
            data[i] = rand() % 0xff;
        }
    }
}

int main(int argc, char *argv[])
{
    // 随机初始化数据data
    init_data(1);
    // init_data(2);

    int length = 16;
    int off = 0;
    unsigned char buf[DATA_LEN];
    while (length >= 16)
    {
        length = stream_read_data(buf + off, length, off);
        off += length;
    }

    // 比较是否相等
    int ret;
    ret = memcmp(data, buf, DATA_LEN);
    if (ret == 0)
    {
        printf("data, buff 内存相同, ret=%d\n", ret);
    }
    else
    {
        printf("--> data, buff 内存不相同, ret=%d\n", ret);
    }

    return 0;
}

/* 运行结果:
data, buff 内存相同, ret=0

*/
